home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / vol_100 / 182_01 / anybase.c < prev    next >
Text File  |  1990-07-30  |  2KB  |  59 lines

  1. /**************************** ANYBASE *******************************
  2.  
  3.                            by dAN mYERS
  4.  
  5. ANYBASE performs numeric conversion between two positive integers in
  6. any base. Because the program uses the ASCII representation of a
  7. number for I/O, litterally ANY base can be figured; interpretation
  8. however, is up to you! Note that ANYBASE uses type "long int" for
  9. calculations which should afford plenty of headroom for conversions.
  10.  
  11. ********************************************************************/
  12. #define MAX_ARRAY 64
  13.  
  14. int       i, base, adj_value;
  15. long int  place_value[MAX_ARRAY], *place_ptr, base10_value;
  16. char      num_to_convert[MAX_ARRAY], *num_ptr;
  17.  
  18. main () {
  19.     place_value[0] = 1;
  20.     base10_value = i = 0;
  21.  
  22. /******************** CONVERT TO BASE 10 **********************/
  23.     printf ("What base is the number to convert in?\n");
  24.     scanf ("%d", &base);
  25.     printf ("Enter the base %d number\n", base);
  26.     scanf ("%s", num_to_convert);
  27.  
  28.     num_ptr = &num_to_convert[strlen(num_to_convert)];
  29.     while (--num_ptr >= num_to_convert) {
  30.          if (*num_ptr < 58)
  31.               adj_value = *num_ptr - '0';
  32.          else
  33.               adj_value = *num_ptr - ('A' - 10);
  34.          base10_value += adj_value * place_value[i];
  35.          place_value[++i] = place_value[i-1] * base;
  36.     }
  37. /******************* CONVERT TO REQUESTED BASE ****************/
  38.     printf ("What base do you want to convert to?\n");
  39.     scanf  ("%d", &base);
  40.  
  41.     place_ptr = place_value;
  42.     do {
  43.          *place_ptr++ = base10_value % base;
  44.          base10_value /= base;
  45.     } while (base10_value >= base);
  46.     *place_ptr = base10_value;
  47.  
  48.     printf ("The base %d equivilent is:\n", base);
  49.     do {
  50.          if (*place_ptr <= 9)
  51.               printf ("%c", *place_ptr + '0');
  52.          else
  53.               printf ("%c", *place_ptr + ('A' - 10));
  54.     } while (--place_ptr >= place_value);
  55.  
  56.     printf ("\n\n");
  57.     main ();
  58. }
  59.